﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace wfaResClient
{
    class UploadClass
    {
        /// <summary>
        /// 没有录音情况下上传信息
        /// </summary>
        public void upFile(string uid, string aid, string name, string ipone, string callType, string callState, string creaTime, string updatetime,string URL)
        {
            NameValueCollection nvc = new NameValueCollection()
            {
                { "uid",uid},
                { "aid",aid},
                { "url",""},
                { "name",name},
                { "ipone",ipone},
                { "callType",callType},
                { "callState",callState},
                { "creatTime",creaTime},
                { "updateTime",updatetime}
            };
            WebClient WebClientObj = new WebClient();
            byte[] byRemoteInfo = WebClientObj.UploadValues(URL, "POST", nvc);
            //下面都没用啦，就上面一句话就可以了 
            string sRemoteInfo = Encoding.Default.GetString(byRemoteInfo);
            //这是获取返回信息

           MessageBox.Show(sRemoteInfo);
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="uid">登录窗体的账号</param>
        /// <param name="adi">设备电话号码</param>
        /// <param name="name">通讯上没姓名就显示为空</param>
        /// <param name="ipone">当前拨出的电话号码</param>
        /// <param name="callType">拨打的类型0拨1接</param>
        /// <param name="callState">返回的类型0挂断1接听</param>
        /// <param name="creaTime">拨打时间</param>
        /// <param name="updatetime">挂断时间</param>
        /// <param name="fileUrl">上传的文件路径</param>
        public void upFile(string uid, string aid, string name, string ipone, string callType, string callState, string creaTime, string updatetime, string fileUrl,string URL)
        {
            NameValueCollection nvc = new NameValueCollection()
            {
                { "uid",uid},
                { "aid",aid},
                { "url",""},
                { "name",name},
                { "ipone",ipone},
                { "callType",callType},
                { "callState",callState},
                { "creatTime",creaTime},
                { "updateTime",updatetime}
            };
            HttpUploadFile(URL, fileUrl,"file", "wav", nvc);
        }
        /// <summary>
        /// 上传数据
        /// </summary>
        /// <param name="url">上传路径</param>
        /// <param name="file">文件地址</param>
        /// <param name="paramName">内容类型</param>
        /// <param name="contentType">内容格式文件</param>
        /// <param name="nvc">需要额外添加的键值对</param>
        public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
        {
            //MessageBox.Show(string.Format("Uploading {0} to {1}", file, url));
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes =Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");//\r\n真正的换行
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;//通过http上传文件的协议
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = CredentialCache.DefaultCredentials;
            Stream rs = wr.GetRequestStream();//写入上面信息进stream rs
            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";//表单数据模板
            foreach (string key in nvc.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }

            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header = string.Format(headerTemplate, paramName, file, contentType);
            byte[] headerbytes = Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();
            byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();
            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                if (reader2.ReadToEnd() != "success")
                {
                    MessageBox.Show("录音同步失败，请检查网络","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); 
                }
                else
                {
                    try
                    {
                        string[] files = Directory.GetFiles(file);
                        int count = files.Length;
                        for (int i = 0; i < count; i++)
                        {
                            File.Delete(files[i]);//删除文件
                        }
                        Log.WriteLog("上传文件成功！" + file);
                    }
                    catch(Exception ex)
                    {
                        Log.WriteLog(ex.ToString());
                    }
                }
                Log.WriteLog(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
            }
            catch (Exception ex)
            {
                Log.WriteLog("Error uploading file" + ex);
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                wr = null;
            }
        }
    }
}
